﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;

namespace WebUI.Controls
{
    public partial class InvoiceDetailsCtrl : BaseListControl, IListControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
        }

        public int DumpID
        {
            get
            {
                if (ViewState[ClientID + "_DumpID"] == null || !(ViewState[ClientID + "_DumpID"] is int))
                    ViewState[ClientID + "_DumpID"] = (int)0;
                return (int)ViewState[ClientID + "_DumpID"];
            }
            set { ViewState[ClientID + "_DumpID"] = value; }
        }

        public Decimal TotalAmt
        {
            get
            {
                if (ViewState[ClientID + "_TotalAmt"] == null || !(ViewState[ClientID + "_TotalAmt"] is Decimal))
                    ViewState[ClientID + "_TotalAmt"] = (Decimal)0;
                return (Decimal)ViewState[ClientID + "_TotalAmt"];
            }
            set { ViewState[ClientID + "_TotalAmt"] = value; }
        }

        public Decimal TotalGST
        {
            get
            {
                if (ViewState[ClientID + "_TotalGST"] == null || !(ViewState[ClientID + "_TotalGST"] is Decimal))
                    ViewState[ClientID + "_TotalGST"] = (Decimal)0;
                return (Decimal)ViewState[ClientID + "_TotalGST"];
            }
            set { ViewState[ClientID + "_TotalGST"] = value; }
        }


        public InvoiceDetails SaleItems
        {
            get { return (InvoiceDetails)SourceObject; }
            set { SourceObject = value; }
        }

        public void AdjustPrice(int price)
        {
            if (SaleItems == null || SaleItems.RowCount == 0)
                return;

            string oldFilter = SaleItems.Filter;

            try
            {
                SaleItems.Filter = InvoiceDetails.ColumnNames.ItemType + "=" + ((int)Invoices.InvoiceCategories.Sale).ToString();

                SaleItems.Rewind();
                String prodIds = "";
                for (int i = 0; i < SaleItems.RowCount; i++)
                {
                    if (i < SaleItems.RowCount - 1)
                        prodIds += SaleItems.ProductID.ToString() + ",";
                    else
                        prodIds += SaleItems.ProductID.ToString();

                    SaleItems.MoveNext();
                }

                Products p = Products.GetProductsByIds(prodIds);

                SaleItems.Rewind();
                for (int i = 0; i < SaleItems.RowCount; i++)
                {
                    p.Filter = "ID=" + SaleItems.ProductID;
                    if (price == CustomerType.CustomerPrice.SalePrice)
                        SaleItems.UnitPrice = p.SalePrice;
                    else if (price == CustomerType.CustomerPrice.DealerPrice)
                        SaleItems.UnitPrice = p.DealerPrice;
                    else
                        SaleItems.UnitPrice = p.PartnerPrice;

                    Decimal discountAmt = SaleItems.Discount;
                    Decimal total = (Decimal)(SaleItems.UnitPrice * SaleItems.Quantity) - discountAmt;
                    Decimal gst = SaleItems.GST > 0 ? Math.Round(total * SysVars.GST / (SysVars.GST + 100), 2) : 0;

                    SaleItems.Total = total;
                    SaleItems.GST = gst;

                    SaleItems.MoveNext();
                }
                SaleItems.Filter = oldFilter;
                UpdateTotalAmt();
                Refresh();
            }
            catch (Exception ex)
            {
                SaleItems.Filter = oldFilter;
                ErrorLog.WriteToFile("InvoiceDetailsCtrl.ascx.cs", "AdjustPrice", ex.StackTrace);
            }
        }

        #region IListControl Members

        public void DeleteCheckedItems()
        {
            String checkedItemID = "";
            for (int i = 0; i < grid.Items.Count; i++)
            {
                DataGridItem item = grid.Items[i];
                Control ctrl = item.FindControl("cbSelect");
                if (ctrl != null && ctrl is CheckBox && ((CheckBox)ctrl).Checked && ((CheckBox)ctrl).Attributes["ItemID"] != null)
                    checkedItemID += ((CheckBox)ctrl).Attributes["ItemID"].ToString() + ",";
            }
            if (checkedItemID != "")
                checkedItemID = checkedItemID.Remove(checkedItemID.Length - 1);
            checkedItemID = "(" + checkedItemID + ")";

            String oldFilter = Filter;
            if (!String.IsNullOrEmpty(oldFilter))
                Filter = Filter + " and (" + InvoiceDetails.ColumnNames.ID + " in " + checkedItemID + ")";
            else
                Filter = InvoiceDetails.ColumnNames.ID + " in " + checkedItemID;

            SaleItems.Rewind();
            while(SaleItems.RowCount > 0)
            {
                SaleItems.MarkAsDeleted();
                SaleItems.MoveNext();
            }

            //if (!SaveOnCommit)
            //    SaleItems.Save();

            Filter = oldFilter;
            UpdateTotalAmt();
        }

        public void DeleteSelectedItem()
        {
            throw new NotImplementedException();
        }

        public void AddNewItem(MyGeneration.dOOdads.SqlClientEntity newItem)
        {
            throw new NotImplementedException();
        }

        public void UpdateItem(MyGeneration.dOOdads.SqlClientEntity updatedItem)
        {
            throw new NotImplementedException();
        }

        #endregion

        public void AddIMEI(string imei, int price)
        {
            String oldFilter = "";
            try
            {
                if (SaleItems == null)
                    SaleItems = new InvoiceDetails();

                oldFilter = SaleItems.Filter;
                SaleItems.Filter = "IMEI = '" + imei + "'";
                if (SaleItems.RowCount > 0)
                {
                    SaleItems.Filter = oldFilter;
                    ShowErrorMessage(grid, String.Format("(*) IMEI {0} has already been added. Please choose another one.", imei));
                    if (SaleItems.IsColumnNull("ID"))
                        SaleItems.MarkAsDeleted();
                    return;
                }
                else
                {
                    SaleItems.Filter = oldFilter;
                    SaleItems.AddNew();
                }

                View_ProductDetails prodDetails = View_ProductDetails.GetAvailableProductDetailsByIMEI(imei);
                if (prodDetails.RowCount > 0)
                {
                    Decimal salePrice = 0;
                    if (price == CustomerType.CustomerPrice.SalePrice)
                        salePrice = prodDetails.SalePrice;
                    else if (price == CustomerType.CustomerPrice.DealerPrice)
                        salePrice = prodDetails.DealerPrice;
                    else if (price == CustomerType.CustomerPrice.PartnerPrice)
                        salePrice = prodDetails.PartnerPrice;

                    Decimal total = (Decimal)(salePrice * 1);
                    Decimal gst = prodDetails.GST ? Math.Round(total * SysVars.GST / (SysVars.GST + 100), 2) : 0;
                    String desc = prodDetails.ProductName;
                    if (!string.IsNullOrEmpty(imei))
                    {
                        desc += string.Format("<br/><span class='hintBold'>IMEI/Serial: {0} </span>", imei);
                    }
                    SaleItems.ID = --DumpID;
                    SaleItems.AddInfoPlus(0, prodDetails.ProductID, imei, prodDetails.ProductName + "(IMEI:" + imei + ")", 1,
                        gst, salePrice, prodDetails.Cost, desc);
                    SaleItems.ItemType = (byte)Invoices.InvoiceCategories.Sale;
                }
                else
                {
                    SaleItems.Filter = oldFilter;
                    ShowErrorMessage(grid, (String.Format("(*) IMEI {0} is not available.", imei)));
                    if (SaleItems.IsColumnNull("ID"))
                        SaleItems.MarkAsDeleted();
                    return;
                }

                SaleItems.Filter = oldFilter;
                UpdateTotalAmt();
                Refresh();
                
            }
            catch(Exception ex)
            {
                if (SaleItems.IsColumnNull("ID"))
                    SaleItems.MarkAsDeleted();
                SaleItems.Filter = oldFilter;
                ErrorLog.WriteToFile("InvoiceDetailsCtrl.ascx.cs", "AddIMEI", ex.Message);
                ShowErrorMessage(grid, "(*) Error: " + ex.Message);
            }
        }

        public void AddRefundedIMEI(string imei, int price)
        {
            String oldFilter = "";
            try
            {
                if (SaleItems == null)
                    SaleItems = new InvoiceDetails();

                oldFilter = SaleItems.Filter;
                SaleItems.Filter = "IMEI = '" + imei + "'";
                if (SaleItems.RowCount > 0)
                {
                    SaleItems.Filter = oldFilter;
                    ShowErrorMessage(grid, String.Format("(*) IMEI {0} has already been added. Please choose another one.", imei));
                    if (SaleItems.IsColumnNull("ID"))
                        SaleItems.MarkAsDeleted();
                    return;
                }
                else
                {
                    SaleItems.Filter = oldFilter;
                    SaleItems.AddNew();
                }

                View_ProductDetails prodDetails = View_ProductDetails.GetSaledProductDetailsByIMEI(imei);
                if (prodDetails.RowCount > 0)
                {
                    Decimal salePrice = 0;
                    if (price == CustomerType.CustomerPrice.SalePrice)
                        salePrice = prodDetails.SalePrice;
                    else if (price == CustomerType.CustomerPrice.DealerPrice)
                        salePrice = prodDetails.DealerPrice;
                    else if (price == CustomerType.CustomerPrice.PartnerPrice)
                        salePrice = prodDetails.PartnerPrice;

                    Decimal total = (Decimal)(salePrice * 1);
                    Decimal gst = prodDetails.GST ? Math.Round(total * SysVars.GST / (SysVars.GST + 100), 2) : 0;
                    String desc = prodDetails.ProductName;
                    if (!string.IsNullOrEmpty(imei))
                    {
                        desc += string.Format("<br/><span class='hintBold'>IMEI/Serial: {0} </span>", imei);
                    }
                    SaleItems.ID = --DumpID;
                    SaleItems.AddInfoPlus(0, prodDetails.ProductID, imei, prodDetails.ProductName + "(IMEI:" + imei + ")", 1,
                        gst, salePrice, prodDetails.Cost, desc);
                    SaleItems.ItemType = (byte)Invoices.InvoiceCategories.Sale;
                }
                else
                {
                    SaleItems.Filter = oldFilter;
                    ShowErrorMessage(grid, (String.Format("(*) IMEI {0} is not available.", imei)));
                    if (SaleItems.IsColumnNull("ID"))
                        SaleItems.MarkAsDeleted();
                    return;
                }

                SaleItems.Filter = oldFilter;
                UpdateTotalAmt();
                Refresh();

            }
            catch (Exception ex)
            {
                if (SaleItems.IsColumnNull("ID"))
                    SaleItems.MarkAsDeleted();
                SaleItems.Filter = oldFilter;
                ErrorLog.WriteToFile("InvoiceDetailsCtrl.ascx.cs", "AddIMEI", ex.Message);
                ShowErrorMessage(grid, "(*) Error: " + ex.Message);
            }
        }

        public void AddRefundIMEI(int modelID, string productName, string imei, decimal salePrice)
        {
            String oldFilter = "";
            try
            {
                if (SaleItems == null)
                    SaleItems = new InvoiceDetails();

                oldFilter = SaleItems.Filter;
                SaleItems.Filter = "IMEI = '" + imei + "'";
                if (SaleItems.RowCount > 0)
                {
                    SaleItems.Filter = oldFilter;
                    ShowErrorMessage(grid, String.Format("(*) IMEI {0} has already been added. Please choose another one.", imei));
                    if (SaleItems.IsColumnNull("ID"))
                        SaleItems.MarkAsDeleted();
                    return;
                }
                else
                {
                    SaleItems.Filter = oldFilter;
                    SaleItems.AddNew();
                }
                Decimal total = (Decimal)(salePrice * 1);
                Decimal gst = 0;
                String desc = productName;
                if (!string.IsNullOrEmpty(imei))
                {
                    desc += string.Format("<br/><span class='hintBold'>IMEI/Serial: {0} </span>", imei);
                }
                SaleItems.ID = --DumpID;
                SaleItems.AddInfoPlus(0, modelID, imei, productName + "(IMEI:" + imei + ")", 1,
                    gst, salePrice, 0, desc);
                SaleItems.ItemType = (byte)Invoices.InvoiceCategories.Sale;

                SaleItems.Filter = oldFilter;
                UpdateTotalAmt();
                Refresh();

            }
            catch (Exception ex)
            {
                if (SaleItems.IsColumnNull("ID"))
                    SaleItems.MarkAsDeleted();
                SaleItems.Filter = oldFilter;
                ErrorLog.WriteToFile("InvoiceDetailsCtrl.ascx.cs", "AddIMEI", ex.Message);
                ShowErrorMessage(grid, "(*) Error: " + ex.Message);
            }
        }

        public void AddNonIMEIProduct(int productID, int qty, int price)
        {
            String oldFilter = "";
            try
            {
                if (SaleItems == null)
                    SaleItems = new InvoiceDetails();

                oldFilter = SaleItems.Filter;
                SaleItems.Filter = "ProductID = " + productID + " and (IMEI = '' or IMEI is NULL)";
                if (SaleItems.RowCount <= 0)
                    SaleItems.AddNew();
                else
                    qty += SaleItems.Quantity;

                Products prod = new Products();
                prod.LoadByPrimaryKey(productID);

                if (prod.Quantity < qty)
                {
                    if (SaleItems.IsColumnNull("ID"))//new item
                        SaleItems.MarkAsDeleted();
                    SaleItems.Filter = oldFilter;
                    ShowErrorMessage(grid, ("(*) Out of stock! Current Quantity = " + prod.Quantity));
                    return;
                }
                else
                {
                    if (prod.RowCount > 0)
                    {
                        Decimal salePrice = 0;
                        if (price == CustomerType.CustomerPrice.SalePrice)
                            salePrice = prod.SalePrice;
                        else if (price == CustomerType.CustomerPrice.DealerPrice)
                            salePrice = prod.DealerPrice;
                        else if (price == CustomerType.CustomerPrice.PartnerPrice)
                            salePrice = prod.PartnerPrice;

                        Decimal total = (Decimal)(salePrice * qty);
                        Decimal gst = prod.GST ? Math.Round(total * SysVars.GST / (SysVars.GST + 100), 2) : 0;

                        SaleItems.ID = --DumpID;
                        SaleItems.AddInfoPlus(0, prod.ID, "", prod.ProductName, qty, gst, salePrice, prod.Cost, prod.ProductName);
                        SaleItems.ItemType = (byte)Invoices.InvoiceCategories.Sale;
                    }
                    else
                    {
                        SaleItems.Filter = oldFilter;
                        ShowErrorMessage(grid,  ("(*) Product is not available."));
                        if (SaleItems.IsColumnNull("ID"))
                            SaleItems.MarkAsDeleted();
                        return;
                    }
                }

                SaleItems.Filter = oldFilter;
                UpdateTotalAmt();
                Refresh();
                
            }
            catch (Exception ex)
            {
                if (SaleItems.IsColumnNull("ID"))
                    SaleItems.MarkAsDeleted();
                SaleItems.Filter = oldFilter;
                ErrorLog.WriteToFile("InvoiceDetailsCtrl.ascx.cs", "AddNonIMEIProduct", ex.Message);
                ShowErrorMessage(grid, "(*) Error: " + ex.Message);
            }
        }

        public void AddBusinessCard(int productID, string name, int qty, decimal price, decimal gst)
        {
            String oldFilter = "";
            try
            {
                if (SaleItems == null)
                    SaleItems = new InvoiceDetails();

                oldFilter = SaleItems.Filter;
                SaleItems.Filter = "ProductID = " + productID + " and (IMEI = '' or IMEI is NULL)";

                if (SaleItems.RowCount <= 0)
                    SaleItems.AddNew();
                else
                    qty += SaleItems.Quantity;

                SaleItems.ID = --DumpID;
                SaleItems.AddInfoPlus(0, productID, "", name, qty, gst, price, 0, name);
                SaleItems.ItemType = (byte)Invoices.InvoiceCategories.BusinessCard;

                SaleItems.Filter = oldFilter;

                UpdateTotalAmt();
                Refresh();

            }
            catch (Exception ex)
            {
                if (SaleItems.IsColumnNull("ID"))
                    SaleItems.MarkAsDeleted();
                SaleItems.Filter = oldFilter;
                ErrorLog.WriteToFile("InvoiceDetailsCtrl.ascx.cs", "AddNonIMEIProduct", ex.Message);
                ShowErrorMessage(grid, "(*) Error: " + ex.Message);
            }
        }

        public void AddRefundedNonIMEIProduct(int productID, int qty, int price)
        {
            String oldFilter = "";
            try
            {
                if (SaleItems == null)
                    SaleItems = new InvoiceDetails();

                oldFilter = SaleItems.Filter;
                SaleItems.Filter = "ProductID = " + productID + " and (IMEI = '' or IMEI is NULL)";
                if (SaleItems.RowCount <= 0)
                    SaleItems.AddNew();
                else
                    qty += SaleItems.Quantity;

                Products prod = new Products();
                prod.LoadByPrimaryKey(productID);

                if (prod.RowCount > 0)
                {
                    Decimal salePrice = 0;
                    if (price == CustomerType.CustomerPrice.SalePrice)
                        salePrice = prod.SalePrice;
                    else if (price == CustomerType.CustomerPrice.DealerPrice)
                        salePrice = prod.DealerPrice;
                    else if (price == CustomerType.CustomerPrice.PartnerPrice)
                        salePrice = prod.PartnerPrice;

                    Decimal total = (Decimal)(salePrice * qty);
                    Decimal gst = prod.GST ? Math.Round(total * SysVars.GST / (SysVars.GST + 100), 2) : 0;

                    SaleItems.ID = --DumpID;
                    SaleItems.AddInfoPlus(0, prod.ID, "", prod.ProductName, qty, gst, salePrice, prod.Cost, prod.ProductName);
                    SaleItems.ItemType = (byte)Invoices.InvoiceCategories.Sale;
                }
                else
                {
                    SaleItems.Filter = oldFilter;
                    ShowErrorMessage(grid, ("(*) Product is not available."));
                    if (SaleItems.IsColumnNull("ID"))
                        SaleItems.MarkAsDeleted();
                    return;
                }
                
                SaleItems.Filter = oldFilter;
                UpdateTotalAmt();
                Refresh();

            }
            catch (Exception ex)
            {
                if (SaleItems.IsColumnNull("ID"))
                    SaleItems.MarkAsDeleted();
                SaleItems.Filter = oldFilter;
                ErrorLog.WriteToFile("InvoiceDetailsCtrl.ascx.cs", "AddNonIMEIProduct", ex.Message);
                ShowErrorMessage(grid, "(*) Error: " + ex.Message);
            }
        }

        public void AddRepair(int repairID)
        {
            String oldFilter = "";
            try
            {
                if (SaleItems == null)
                    SaleItems = new InvoiceDetails();

                oldFilter = SaleItems.Filter;
                SaleItems.AddNew();

                View_RepairJobs rp = View_RepairJobs.GetJobByID(repairID);

                if(rp.RowCount > 0)
                {
                    RepairJobProblems prob = RepairJobProblems.GetProblemsByRepairID(repairID);
                    String probStr = "";
                    Decimal salePrice = 0;
                    for(int i = 0; i < prob.RowCount; i++)
                    {
                        salePrice += prob.Price;
                        probStr += ", " + prob.s_Description;

                        prob.MoveNext();
                    }
                    Decimal total = (Decimal)(salePrice);
                    Decimal gst = Math.Round(total * SysVars.GST / (SysVars.GST + 100), 2);
                    String desc = string.Format("{1}{2}<br/><span class='hintBold'>IMEI/Serial: {0}</span>", rp.IMEI, rp.s_BrandName + " " + rp.s_ModelName, probStr);
                    SaleItems.ID = --DumpID;
                    SaleItems.AddInfoPlus(0, repairID, rp.s_IMEI, rp.s_BrandName + " " + rp.s_ModelName, 1, gst, salePrice, 0, desc);
                    SaleItems.ItemType = (byte)Invoices.InvoiceCategories.Repair;
                }
                else
                {
                    SaleItems.Filter = oldFilter;
                    ShowErrorMessage(grid,  ("(*) Item is not available."));
                    if (SaleItems.IsColumnNull("ID"))
                        SaleItems.MarkAsDeleted();
                    return;
                }

                SaleItems.Filter = oldFilter;
                UpdateTotalAmt();
                Refresh();

            }
            catch (Exception ex)
            {
                if (SaleItems.IsColumnNull("ID"))
                    SaleItems.MarkAsDeleted();
                SaleItems.Filter = oldFilter;
                ErrorLog.WriteToFile("InvoiceDetailsCtrl.ascx.cs", "AddNonIMEIProduct", ex.Message);
                ShowErrorMessage(grid, "(*) Error: " + ex.Message);
            }
        }

        public void UpdateTotalAmt()
        {
            TotalGST = 0;
            TotalAmt = 0;

            if (SourceObject != null && SourceObject.RowCount > 0 && !SourceObject.IsColumnNull("GST") && !SourceObject.IsColumnNull("Total"))
            {
                SourceObject.Rewind();
                for (int i = 0; i < SourceObject.RowCount; i++)
                {
                    TotalAmt += (decimal)SourceObject.GetColumn("Total");
                    TotalGST += (decimal)SourceObject.GetColumn("GST");
                    SourceObject.MoveNext();
                }
            }
        }

        protected override void grid_OnItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Footer)
            {
                e.Item.Cells[6].Text = TotalGST == null ? string.Format("{0:C}", 0) : string.Format("{0:C}", TotalGST);
                e.Item.Cells[7].Text = TotalAmt == null ? string.Format("{0:C}", 0) : string.Format("{0:C}", TotalAmt);
                e.Item.Cells[6].Attributes.Add("align", "right");
                e.Item.Cells[7].Attributes.Add("align", "right");
            }
        }

        public void DiscountAllByPercentage(int discount)
        {
            SaleItems.Rewind();

            for (int i = 0; i < SaleItems.RowCount; i++)
            {
                Decimal total = (Decimal)(SaleItems.UnitPrice * SaleItems.Quantity);
                Decimal gst = SaleItems.GST > 0 ? Math.Round(total * SysVars.GST / (SysVars.GST + 100), 2) : 0;

                Decimal discountAmt = discount * total / 100;
                Decimal discountGST = discount * gst / 100;
                SaleItems.Discount = discountAmt;

                SaleItems.Total = Math.Round(total - discountAmt, 2);
                SaleItems.GST = Math.Round(gst - discountGST, 2);

                SaleItems.MoveNext();
            }

            UpdateTotalAmt();
            Refresh();
        }

        //public void DiscountAllByAmt(decimal discountAmt)
        //{
        //    SaleItems.Rewind();

        //    for (int i = 0; i < SaleItems.RowCount; i++)
        //    {
        //        Decimal total = (Decimal)(SaleItems.UnitPrice * SaleItems.Quantity);
        //        total -= discountAmt;

        //        SaleItems.Discount = discountAmt;

        //        Decimal gst = SaleItems.GST > 0 ? Math.Round(total * SysVars.GST / (SysVars.GST + 100), 2) : 0;

        //        SaleItems.Total = total - discountAmt;
        //        SaleItems.GST = gst;

        //        SaleItems.MoveNext();
        //    }

        //    UpdateTotalAmt();
        //    Refresh();
        //}
    }
}